package com.lam.common.components.lang;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import com.lam.common.context.AuthTypeEnum;
import com.lam.common.context.TokenUtils;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;

/**
 * 国际化语言工具包
 * @author lam
 *
 */
public class LangUtil {
	
	private static LangService langService;
	
	public static LangService getLangService() {
		if(langService == null) {
			langService = SpringUtils.getBean(LangService.class);
		}
		return langService;
	}
	
	/**
	 * 获取当前国际化语言环境下的内容
	 * @param key
	 * @param args 格式化变量
	 * @return
	 */
	public static String getCurLangVal(String key, Object ... args) {
		String[] langs = getCurLang().split(":");
		String val = LangUtil.getLanByKey(langs[0], langs[1], key);
		if(args == null || args.length==0) {
			return val;
		}
		return MessageFormat.format(val, args);
	}
	
	/**
     * 获取 request 里传递的 locale
     * @param request
     * @return
     */
    public static String getCurLacole() {
    	String lang = getCurLang();
        return lang.split(":")[0];
    }
    
    /**
     * 获取 request 里传递的 locale
     * @param request
     * @return
     */
    public static String getCurCategory() {
    	String lang = getCurLang();
        return lang.split(":")[1];
    }
    
    /**
     * 获取 request 里传递的 lang
     * @param request
     * @return
     */
    public static String getCurLang() {
        return getCurLang(null);
    }
    
    /**
     * 获取 request 里传递的 lang
     * @param request
     * @return
     */
    public static String getCurLang(HttpServletRequest request) {
    	if(request == null) {
    		request = SpringUtils.getRequest();
    	}
        String lang = request.getHeader("X-Lang");
        if (lang == null) {
        	lang = request.getParameter("_X_Lang");
        }
        if(StringUtils.isBlank(lang)) {
        	if(AuthTypeEnum.ADMIN == TokenUtils.getAuthType(request)){
        		lang = "zh-CN:adminHomePage";
        	}else {
        		lang = "zh-CN:frontHomePage";
        	}
        }
        return lang;
    }
	
	public static String getAdmLangByKey(String lang, String key) {
		return getLanByKey(lang, "adminHomePage", key);
	}
	
	public static String getFrontLangByKey(String lang, String key) {
		return getLanByKey(lang, "frontHomePage", key);
	}
	
	public static String getLanByKey(String lang, String category, String key) {
		String lanVal = getLangByKey2(lang, category, key);
		return (lanVal == null || StringUtils.isBlank(lanVal))?key:lanVal;
	}
	
	public static String getLangByKey2(String lang, String category, String key) {
		return getLangService().getLangValueByKey(lang, category, key);
	}

}
